package com.tiger.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.mapper.base.AdminMapper;
import com.tiger.pojo.base.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/3/10
 */
@Slf4j
@RestController
public class AdminLoginController {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Value("${info.email.url}")
    private String emailUrl;
    @Value("${info.email.login-title}")
    private String loginTitle;
    @Value("${info.email.pref-content}")
    private String prefContent;
    @Value("${info.email.suf-content}")
    private String sufContent;

    /**
     * 通过用户名和邮箱获取登录授权码
     * @param adminName
     * @param email
     * @return
     */
    @RequestMapping(value = "/adminLog/getLoginCode/{adminName}/{email}",name = "获取登录授权码/admin")
    public String getLoginCode(@PathVariable String adminName, @PathVariable String email){
        try {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            wrapper.eq("admin_name",adminName);
            wrapper.eq("admin_email",email);
            List<Admin> admins = adminMapper.selectList(wrapper);
            if (admins.size()!=1){
                return "false";
            }else {
                // 设置临时adminIdTemp
                httpServletRequest.getSession().setAttribute("adminIdTemp",admins.get(0).getAdminId());

                String authorCode = UUID.randomUUID()+"";
                String content = emailContent(authorCode);
                sendHtmlMail(emailUrl,email,loginTitle,content);
                httpServletRequest.getSession().setAttribute("code",authorCode);
                return "true";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    private String emailContent(String authorCode) {

        return prefContent+ authorCode + sufContent;
    }

    /**
     * 发布邮件
     * @param from
     * @param targetEmail
     * @param subject
     * @param content
     * @throws Exception
     */
    @Async  // 异步任务
    public void sendHtmlMail(String from, String targetEmail,String subject,String content) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        messageHelper = new MimeMessageHelper(message,true);
        messageHelper.setFrom(from);
        messageHelper.setTo(targetEmail);
        message.setSubject(subject);
        messageHelper.setText(content,true); // true表示使用HTML邮件
        javaMailSender.send(message);
    }

    @RequestMapping(value = "/adminLog/login/{code}", name = "登录/admin")
    public String login(@PathVariable String code){
        try {
            if (!code.equals(httpServletRequest.getSession().getAttribute("code"))){
                return "false";
            }else{
                httpServletRequest.getSession().removeAttribute("code"); // 销毁session
                httpServletRequest.getSession().setAttribute("adminId",httpServletRequest.getSession().getAttribute("adminIdTemp"));
                httpServletRequest.getSession().removeAttribute("adminIdTemp"); // 销毁 adminIdTemp
                return "true";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    @RequestMapping(value = "/adminLog/logout",name = "退出/admin")
    public String logout(){
        try {
            httpServletRequest.getSession().removeAttribute("adminId");
            return "true";
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }
}
